package com.doc.controller.sys;


import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.subject.Subject;

import com.doc.model.ApiDoc;
import com.doc.model.ApiProject;
import com.jfinal.plugin.activerecord.Record;
import com.wjwframework.jfinal.controller.BaseController;
import com.wjwframework.jfinal.vo.Response;
import com.wjwframework.jfinal.web.constant.Constants;
import com.wjwframework.jfinal.web.model.SysUser;
import com.wjwframework.jfinal.web.shiro.ShiroUtils;
import com.wjwframework.jfinal.web.shiro.UserToken;

public class MainController extends BaseController {
	
	private ApiProject proDao=ApiProject.dao;
	
	private ApiDoc docDao=ApiDoc.dao;
	
	/**
     * api文档首页
     */
    public void index(){
    	String rootId= getPara("rootId");//获取根项目
    	List<ApiProject> rootList=proDao.find("SELECT * FROM api_project where state=1 AND parent_id IS null order by seq asc");//查询所有根栏目
    	ApiProject bean = null;
    	String sql = " SELECT * FROM api_project WHERE state=1 AND id=? AND parent_id IS null ";
    	if(StringUtils.isNotBlank(rootId) && proDao.findFirst(sql,rootId)!=null){
    		bean = proDao.findFirst(sql, rootId);
    	}else{
    		bean = rootList.get(0);
    	}
    	
    	List<Record> beanList =  new ArrayList<Record>();
		getListByPid(rootId, beanList);//递归查询子集合
		
		setAttr("rootList", rootList);//当前根项目集合
		setAttr("beanList", beanList);//当前根项目集合(包含对应节点目录文档集合)
    	setAttr("bean", bean);//当前根项目
    	setAttr("req", getRequest());
    	renderFreeMarker("front/api.html");
    }
    /**
     * 根据pId递归查询子集合，如果是节点目录则查询对应文档集合
     * @param id
     * @param list
     */
    private void getListByPid(String id,List<Record> list){
		List<Record> beanList = proDao.findListByParentId(id);//查询所有根项目对象
		list.addAll(beanList);
		for(Record bean : beanList){
			List<Record> itemList = proDao.findListByParentId(bean.getStr("id"));//查询所有根项目对象
			if(itemList.isEmpty()){//如果是节点目录则查询对应文档
				List<ApiDoc> docList=docDao.find("SELECT * FROM api_doc where state!=0 AND project_id=? order by seq asc",bean.get("id"));//查询所有文档
				bean.set("docList", docList!=null&&docList.size()>0?docList:null);//将对应文档集合添加到节点下
				bean.set("node", 1);//是节点目录
			}else{
				bean.set("docList", null);
				bean.set("node", 0);
				getListByPid(bean.getStr("id"), list);
			}
		}
	}
	
    /**
     * 后台登陆页面
     * @return
     */
	public void admin() {
		setAttr("req", getRequest());
		renderFreeMarker("login.html");
	}
	
    /**
     * 后台管理页面
     * @return
     */
	public void main() {
    	SysUser user_session=(SysUser) getSession().getAttribute(Constants.SESSION_USER_KEY);//获取session中的用户
    	if(user_session==null){//如果未登陆则跳转登陆
    		setAttr("req", getRequest());
    		renderFreeMarker("login.html");
    		return;
    	}
		setAttr("req", getRequest());
		setAttr("session", getSession());
		renderFreeMarker("admin/main.html");
	}
	
    /**
     * web登陆action
     * Login
     */
    public void login() {
    	Response response=new Response();
    	SysUser user_session=(SysUser) getSession().getAttribute(Constants.SESSION_USER_KEY);//获取session中的用户
    	if(user_session!=null){//已经登陆过直接返回
    		response.result.put("locate", "main.do");
			renderJson(response);
			return;
    	}
    	
    	SysUser obj=getModel(SysUser.class,"user");
		if (obj == null || obj.getStr("user_name") == null|| obj.getStr("password") == null) {
			response.setErrcode(1);
			renderJson(response);
			return;
		}
		Subject subject = SecurityUtils.getSubject();
		UserToken userToken=new UserToken(obj,true);
		try {
			subject.login(userToken);//登陆授权认证
			if(subject.isAuthenticated()){
				response.result.put("locate", "main.do");
				renderJson(response);
				return;
			}
		} catch (UnknownAccountException e) {
			response.setErrcode(-1);
			response.setMsg("用户名不存在!");
		} catch(IncorrectCredentialsException e){
			response.setErrcode(-1);
			response.setMsg("用户名或密码错误!");
		}catch (LockedAccountException e) {
			response.setErrcode(-1);
			response.setMsg("用户未激活或被锁定，请与管理员联系!");
		}catch (AuthenticationException e) {
			response.setErrcode(-1);
			response.setMsg("未知的登录错误!");
		}
    	renderJson(response);
    }
    
    /**
     * 退出系统
     * @return
     */
	public void exit() {
		Subject subject = SecurityUtils.getSubject();
		subject.logout();
		cleanCache(getResponse());//清除缓存
		Response response=new Response();
		renderJson(response);
	}
	
	/**
	 * 清除缓存
	 */
	private void cleanCache(HttpServletResponse response){
		response.setHeader("Pragma","No-cache");
		response.setHeader("Cache-Control","no-cache"); 
		response.setDateHeader("Expires", 0); 
		response.setHeader("Cache-Control","no-store, no-cache, must-revalidate");
		response.addHeader("Cache-Control", "post-check=0, pre-check=0");
		response.setHeader("Pragma", "no-cache");
	}
	
	/**
	 * Dategrid列表模板获取
	 */
	public void template(){
		Response response=new Response();
		String name=getPara("name");//模板名称
		String url=getPara("url");//获取子集权限
		if(name==null || url==null){
			response.setErrcode(1);
    		response.setMsg("name,url不能为空!");
    		renderJson(response);
    		return;
		}
		//查询该权限下面的操作菜单
		List<Record> pList=ShiroUtils.getPowerListByFatherUrl(url);
		setAttr("powers", pList);//获取菜单集合
		renderFreeMarker("/template/"+name);
	}
	
	/**
	 * 模板渲染获取
	 */
	public void getTemplate(){
		Response response=new Response();
		String url=getPara("url");//模板路径
		if(url==null){
			response.setErrcode(1);
    		response.setMsg("url不能为空!");
    		renderJson(response);
    		return;
		}
		setAttr("req", getRequest());
		renderFreeMarker("/template/"+url);
	}
}